package com.coffee.admin.controller.platform;

import com.alibaba.fastjson.JSONObject;
import com.coffee.admin.api.common.service.RedisService;
import com.coffee.admin.api.merchant.rep.MerchantDetailRep;
import com.coffee.admin.api.merchant.rep.MerchantListRep;
import com.coffee.admin.api.merchant.req.*;
import com.coffee.admin.api.merchant.result.MerchantResult;
import com.coffee.admin.api.merchant.service.MerchantService;
import com.coffee.admin.controller.BaseController;
import com.coffee.admin.utils.WeixinGzhAppletsUtil;
import com.coffee.core.anotation.OperLog;
import com.coffee.core.anotation.PlatformLoginCheck;
import com.coffee.core.entity.LoginUser;
import com.coffee.core.entity.Page;
import com.coffee.core.entity.PagerInfo;
import com.coffee.core.enums.ExceptionEnum;
import com.coffee.core.exception.BusinessException;
import com.coffee.core.result.Result;
import com.coffee.core.util.BeanUtilExt;
import com.coffee.core.util.DateUtil;
import com.coffee.core.util.ToolMobileSegmentResult;
import com.coffee.core.util.ZhongtailClient;
import com.coffee.order.api.inquire.result.WeiXinPushIntegralResult;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("/platform")
public class PlatformMerchantController extends BaseController {

    @DubboReference
    private MerchantService merchantService;
    @DubboReference
    private RedisService redisService;

    private ExecutorService executorService = Executors.newFixedThreadPool(10);

    @OperLog(operModul = "平台-商户管理", operDesc = "查询商户管理列表")
    @PlatformLoginCheck(alias = "MerchantManageListAlias")
    @PostMapping(value = "/merchantList")
    public Result<Page<MerchantListRep>> merchantList(@RequestBody MerchantListReq req, HttpServletRequest request, HttpServletResponse response) {
        PagerInfo pagerInfo = setDefaultPageInfo(req.getPageSize(), req.getPageIndex());
        Page<MerchantListRep> merchantListRepPage = merchantService.getPager(req, pagerInfo);
        return Result.success(merchantListRepPage);
    }

    @OperLog(operModul = "平台-商户管理", operDesc = "查询商户管理列表")
    @PlatformLoginCheck(alias = "MerchantManageListAlias")
    @PostMapping(value = "/supplierAndMerchantList")
    public Result<Page<MerchantListRep>> supplierAndMerchantList(@RequestBody MerchantListReq req, HttpServletRequest request, HttpServletResponse response) {
        PagerInfo pagerInfo = setDefaultPageInfo(req.getPageSize(), req.getPageIndex());
        Page<MerchantListRep> merchantListRepPage = merchantService.getSupplierAndMerchantPager(req, pagerInfo);
        return Result.success(merchantListRepPage);
    }


    @OperLog(operModul = "平台-商户管理-删除商户", operDesc = "商户管理-删除商户")
    @PlatformLoginCheck(alias = "MerchantManageOperationAlias")
    @PostMapping(value = "/merchant/delete")
    public Result<String> merchantDelete(@RequestBody JSONObject json, HttpServletRequest request, HttpServletResponse response) {
        Integer id = json.getInteger("id");
        merchantService.delete(id);
        return Result.success("SUCCESS");
    }


    @OperLog(operModul = "平台-商户管理-新增商户", operDesc = "商户管理-新增商户")
    @PlatformLoginCheck(alias = "MerchantManageOperationAlias")
    @PostMapping(value = "/merchant/add")
    public Result<String> merchantAdd(@RequestBody MerchantAddReq req, HttpServletRequest request, HttpServletResponse response) throws BusinessException {
        MerchantResult result = new MerchantResult();
        BeanUtilExt.copyProperties(result, req);
        ToolMobileSegmentResult mobileSeg = ZhongtailClient.getMobileSeg(req.getMobile());
        result.setCity(mobileSeg.getCity());
        result.setProvince(mobileSeg.getProvince());
        merchantService.add(result);
        return Result.success("SUCCESS");
    }


    @OperLog(operModul = "平台-商户管理-商户详情", operDesc = "商户管理-商户详情")
    @PlatformLoginCheck(alias = "MerchantManageListAlias")
    @PostMapping(value = "/merchant/detail")
    public Result<MerchantDetailRep> merchantDetail(@RequestBody JSONObject json, HttpServletRequest request, HttpServletResponse response) {
        Integer id = json.getInteger("id");
        MerchantDetailRep merchantDetailRep = merchantService.platformGetDetail(id);
        return Result.success(merchantDetailRep);
    }

    @OperLog(operModul = "平台-商户管理-变更手机号", operDesc = "商户管理-变更手机号")
    @PlatformLoginCheck(alias = "MerchantManageOperationAlias")
    @PostMapping(value = "/merchant/updateMobile")
    public Result<String> merchantUpdateMobile(@RequestBody MerchantUpdateMobileReq req, HttpServletRequest request, HttpServletResponse response) {
        try {
            merchantService.updateMobile(req);
            return Result.success("SUCCESS");
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
    }


    @OperLog(operModul = "平台-商户管理-变更密码", operDesc = "商户管理-变更密码")
    @PlatformLoginCheck(alias = "MerchantManageOperationAlias")
    @PostMapping(value = "/merchant/updatePassword")
    public Result<String> merchantUpdatePassword(@RequestBody MerchantUpdatePasswordReq req, HttpServletRequest request, HttpServletResponse response) {
        try {
            merchantService.updatePassword(req);
            return Result.success("SUCCESS");
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
    }

    @OperLog(operModul = "平台-商户管理-变更积分", operDesc = "商户管理-变更积分")
    @PlatformLoginCheck(alias = "MerchantManageOperationAlias")
    @PostMapping(value = "/merchant/updateIntegral")
    public Result<String> merchantUpdateIntegral(@RequestBody MerchantUpdateIntegralReq req, HttpServletRequest request, HttpServletResponse response) {
        try {
            LoginUser platformLoginUser = getSupplier();
            req.setOperationId(platformLoginUser.getPlatformId());
            WeiXinPushIntegralResult weiXinPushIntegralResult = merchantService.updateIntegral(req);
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Object accessToken = redisService.get("accessToken");
                        String accessTokenStr = null;
                        if (accessToken == null) {
                            JSONObject accessToken1 = WeixinGzhAppletsUtil.getGzhAccessToken();
                            accessToken1.put("expires_time", DateUtil.addSeconds(new Date(), accessToken1.getInteger("expires_in")));
                            redisService.set("accessToken", accessToken1);
                            accessTokenStr = accessToken1.getString("access_token");
                        } else {
                            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(accessToken));
                            if (jsonObject.getDate("expires_time").before(new Date())) {
                                JSONObject accessToken2 = WeixinGzhAppletsUtil.getGzhAccessToken();
                                accessToken2.put("expires_time", DateUtil.addSeconds(new Date(), accessToken2.getInteger("expires_in")));
                                redisService.set("accessToken", accessToken2);
                                accessTokenStr = accessToken2.getString("access_token");
                            } else {
                                accessTokenStr = jsonObject.getString("access_token");
                            }
                        }
                        if (StringUtils.isNotEmpty(weiXinPushIntegralResult.getOpenId())) {
                            Map<String, String> content = new HashMap<>();
                            content.put("thing5", weiXinPushIntegralResult.getMerchantName());
                            content.put("const2", "云币可兑换人民币");
                            content.put("amount4", weiXinPushIntegralResult.getIntegralPrice() + "");
                            WeixinGzhAppletsUtil.pushIntegralNew("eaGPbTePt6Vo-8xeZ9XIIKBakrtyPvZHFBS42xyM0I4"
                                    , accessTokenStr, weiXinPushIntegralResult.getOpenId(), content);
                        }
                    } catch (BusinessException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
            return Result.success("SUCCESS");
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
    }

    @OperLog(operModul = "平台-商户管理-变更购买权限", operDesc = "商户管理-变更购买权限")
    @PlatformLoginCheck(alias = "MerchantManageOperationAlias")
    @PostMapping(value = "/merchant/updateBuyPermission")
    public Result<String> updateBuyPermission(@RequestBody MerchantUpdateBuyPermissionReq req, HttpServletRequest request, HttpServletResponse response) {
        try {
            merchantService.updateBuyPermission(req);
            return Result.success("SUCCESS");
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
    }

    @OperLog(operModul = "平台-商户管理-变更商户状态", operDesc = "商户管理-变更商户状态")
    @PlatformLoginCheck(alias = "MerchantManageOperationAlias")
    @PostMapping(value = "/merchant/updateIsEnable")
    public Result<String> updateIsEnable(@RequestBody MerchantUpdateIsEnableReq req, HttpServletRequest request, HttpServletResponse response) {
        try {
            merchantService.updateIsEnable(req);
            return Result.success("SUCCESS");
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
    }

    @OperLog(operModul = "平台-商户管理-变更商户状态", operDesc = "商户管理-变更商户状态")
    @PlatformLoginCheck(alias = "MerchantManageOperationAlias")
    @PostMapping(value = "/merchant/updateRemark")
    public Result<String> updateRemark(@RequestBody JSONObject jsonObject, HttpServletRequest request, HttpServletResponse response) {
        try {
            String remark = jsonObject.getString("remark");
            Integer id = jsonObject.getInteger("id");
            if (StringUtils.isEmpty(remark)) {
                throw BusinessException.build(ExceptionEnum.ERROR_1345);
            }
            MerchantResult merchantResult = new MerchantResult();
            merchantResult.setId(id);
            merchantResult.setRemark(remark);
            merchantService.update(merchantResult);
            return Result.success("SUCCESS");
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
    }


    @OperLog(operModul = "平台-商户管理-变更商户余额", operDesc = "商户管理-变更商户余额")
    @PlatformLoginCheck(alias = "MerchantManageOperationAlias")
    @PostMapping(value = "/merchant/updateBalance")
    public Result<String> updateBalance(@RequestBody MerchantUpdateBalanceReq req, HttpServletRequest request, HttpServletResponse response) {
        try {
            merchantService.updateBalance(req);
            return Result.success("SUCCESS");
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
    }

    @OperLog(operModul = "平台-商户管理-增加商户余额", operDesc = "商户管理-增加商户余额")
    @PlatformLoginCheck(alias = "MerchantManageOperationAlias")
    @PostMapping(value = "/merchant/addBalance")
    public Result<String> addBalance(@RequestBody MerchantUpdateBalanceReq req, HttpServletRequest request, HttpServletResponse response) {
        try {
            merchantService.addBalance(req);
            return Result.success("SUCCESS");
        } catch (BusinessException e) {
            return Result.failed(e.getCode(), e.getMessage());
        }
    }

}
